package com.blog.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blog.dao.MessageMapper;
import com.blog.filter.SensitiveFilter;
import com.blog.pojo.Message;
import com.blog.pojo.Type;
import com.blog.service.MessageService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Copyright (C), 2022
 * Author: 苏大大
 * Date: 2022-05-31 14:38
 * FileName: MessageServiceImpl
 * Description: 留言业务层实现
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    MessageMapper mapper;

    @Resource
    RedisTemplate redisTemplate;

    /**
     * 获取留言列表
     * @return
     */
    @Override
    public List<Message> getMessageList() {
        List<Message> CacheList=mapper.getMessageList();
        if(redisTemplate.opsForValue().get("MessageList")!=null&&redisTemplate.opsForValue().get("MessageList")==CacheList){
            String a=redisTemplate.opsForValue().get("MessageList").toString();
            List<Message> list=(List<Message>) JSON.parseArray(a,Message.class);
            return list;
        }
        if(CacheList!=null){
            //异常设备的json数组,把list转换为json形式数组
            JSONArray jsonArray= JSONObject.parseArray(JSONObject.toJSONString(CacheList));
            //将json形式数组装换为string类型
            String json= jsonArray.toJSONString();
            //将需要缓存的数据缓存入redis
            redisTemplate.opsForValue().set("MessageList",json);
        }
        String a=redisTemplate.opsForValue().get("MessageList").toString();
        List<Message> MessageList=(List<Message>) JSON.parseArray(a,Message.class);
        return MessageList;
    }

    /***
     * 新增留言
     * @param message
     * @return
     */
    @Override
    public boolean add(Message message) {
        //过滤敏感词
        message.setMessageContent(SensitiveFilter.filter(message.getMessageContent().trim()));
        return mapper.add(message)==1;
    }
}
